﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barebones.Components;
using Barebones.Dependencies;
using Microsoft.Xna.Framework.Content;
using Barebones.Xna;
using Microsoft.Xna.Framework.Graphics;

namespace Meat.Resources
{
    public class ResourceLoader : EngineComponent
    {
        ContentManager m_Content;
        GraphicsDevice m_Device;
        Dictionary<String, IResource> m_Resources = new Dictionary<string, IResource>();

        public ContentManager Content
        { get { return m_Content; } }

        public GraphicsDevice Device
        { get { return m_Device; } }

        public override IEnumerable<IDependency> GetDependencies()
        {
            yield break;
        }

        public void AddResource(IResource resource)
        {
            resource.SetLoader(this);
            m_Resources.Add(resource.Name, resource);
        }

        public bool TryGetResource(String name, out IResource res)
        {
            return m_Resources.TryGetValue(name, out res);
        }

        public IResource GetResource(String name)
        {
            IResource res;
            if (!m_Resources.TryGetValue(name, out res))
                throw new InvalidOperationException("Tried to get a non existant resource : " + name);

            return res;
        }

        public void ForceLoadAll()
        {
            foreach (IResource res in m_Resources.Values)
                res.ForceLoad();
        }

        protected override void OnOwnerSet()
        {
            Owner.Forum.RegisterListener<InitializeMessage>(OnInitialize);
            Owner.Forum.RegisterListener<LoadContentMessage>(OnLoad);

            base.OnOwnerSet();
        }

        void OnInitialize(InitializeMessage msg)
        {
            m_Device = msg.Device;
        }

        void OnLoad(LoadContentMessage msg)
        {
            if (m_Content != null)
            {
                m_Content.Unload();

                foreach (var item in m_Resources.Values)
                    item.Reset();
            }

            m_Content = msg.Content;
        }
    }
}
